package com.heima.search.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.model.common.apuser.pojos.ApUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.search.dtos.UserSearchDto;
import com.heima.model.common.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.threadLocal.ApThreadLocalUtil;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {

    @Autowired(required = false)
    private ResponseResult responseResult;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ApUserSearchService apUserSearchService;
    /**
     * ES文章分页搜索
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto)  {
        try {
        //1.检查参数
        if (dto==null|| StringUtils.isBlank(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = ApThreadLocalUtil.getUser();

        //异步调用 保存搜索记录
        if(user != null && dto.getFromIndex() == 0){
            apUserSearchService.insert(dto.getSearchWords(), user.getId());
        }

        //2.创建搜索请求对象，并且指定索引库
        SearchRequest searchRequest = new SearchRequest("app_info_article");
        SearchSourceBuilder searchSorceBuilder = new SearchSourceBuilder();
        //布尔条件查询
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        //2.1关键字查询
        if (dto.getSearchWords()!=null){
            QueryStringQueryBuilder queryStringQueryBuilder = QueryBuilders.queryStringQuery(dto.getSearchWords()).field("title").field("content").defaultField(String.valueOf(Operator.OR));
            boolQueryBuilder.must(queryStringQueryBuilder);

        }
        //小于最小时间
        if (dto.getMinBehotTime()!=null){
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("publishTime").lte(dto.getMinBehotTime().getTime());
            boolQueryBuilder.filter(rangeQueryBuilder);

        }

        //分页
        searchSorceBuilder.from(0);
        searchSorceBuilder.size(dto.getPageSize());

        //排序
        searchRequest.source().sort("publishTime", SortOrder.DESC);

        //高亮
        HighlightBuilder highlight = new HighlightBuilder();
        highlight.field("title");
        highlight.requireFieldMatch(false);
        highlight.preTags("<font style='color: red;font-size:inherit;'>");
        highlight.preTags("</font>");

        searchRequest.source().highlighter(highlight);

        //1.调用es的搜索api
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            //3.结果封装
            return result(response);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }


    private ResponseResult result(SearchResponse response){
        ArrayList<Map> list = new ArrayList<>();

        //1.获取命中的结果
        SearchHit[] hits = response.getHits().getHits();

        for (SearchHit hit : hits) {
            //查获查询结果
            Map<String, Object> map = hit.getSourceAsMap();

            //高亮数据封装
            //如果高亮域中有值
            if (hit.getHighlightFields().size()>0){
                //取出高亮域
                Text[] titles = hit.getHighlightFields().get("title").fragments();
                if (titles.length>0){
                    //把高亮之后h_tile=<font>测试</font>
                    map.put("h_title",titles[0].toString());
                }
            }else {
                //表示没有高亮域，则把h_title=测试
                map.put("h_title",map.get("title"));
            }
            list.add(map);
        }
        return ResponseResult.okResult(list);
    }

}
